package com.mkyong;

import java.util.Calendar;
import java.util.List;

import org.springframework.batch.item.ItemWriter;

public class ExcelItemWriter implements ItemWriter<User> {
	
	private static int rcount = 0;
	private String path;

	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	
	private String prefix;
	
	
	public String getPrefix() {
		return prefix;
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	
	private static String filepath ;
	
	public static String getFilePath(){
		return filepath;
	}


	@Override
	public void write(List<? extends User> items) throws Exception {
		// TODO Auto-generated method stub
		int titleRow = 0;
		ExcelUtils.init();
		ExcelUtils.createSheet("操作日志");
		ExcelUtils.insertTitle(titleRow, 0, "ID");
		ExcelUtils.insertTitle(titleRow, 1, "登录用户");
		ExcelUtils.insertTitle(titleRow, 2, "登录密码");
		ExcelUtils.insertTitle(titleRow, 3, "年龄22");
		if(null != items){
			int row = rcount;
			for(User user : items){
				int id = user.getId();
				String loginUser = user.getUsername();
				String password = user.getPassword();
				int age = user.getAge();
				row = row + 1;
				ExcelUtils.insertData(row, 0, id);
				ExcelUtils.insertData(row, 1, loginUser);
				ExcelUtils.insertData(row, 2, password);
				ExcelUtils.insertData(row, 3, age);
			}
			rcount += items.size();
		}
		try{
			String filename = "";
			Calendar c = Calendar.getInstance();
			int y = c.get(Calendar.YEAR);
			int m = c.get(Calendar.MONTH)+1;
			int d = c.get(Calendar.DAY_OF_MONTH);
			filename = prefix+y+"-"+m+"-"+d+".xls";
			filepath = path+"/"+filename;
			ExcelUtils.output(path,filename);
			System.out.println("total rows = "+rcount);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
}
